﻿using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WisDom.DBContext;
using WisDom.IService;
using WisDom.Models;
using WisDom.Util;

namespace WisDom.Service.Service
{
    public class PackageSetupInfoService : IPackageSetupInfoInterface
    {
        private ApplicationDbContext _dbContext;
        public PackageSetupInfoService(ApplicationDbContext dbContext)
        {
            this._dbContext = dbContext;
        }
        #region 获取数据
        /// <summary>
        /// 获取单个实体
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public Task<PackageSetupInfoEntity> GetEntity(string keyValue)
        {
            return _dbContext.PackageSetupInfoEntitys.FirstOrDefaultAsync(n => n.SetupId == Convert.ToInt32(keyValue));
        }
        
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public Task<List<PackageSetupInfoEntity>> GetList(string queryJson)
        {
            var expression = GetExpression(queryJson);
            return _dbContext.PackageSetupInfoEntitys.Where(expression).ToListAsync();
        }
        /// <summary>
        /// 按照分页进行获取数据
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public Task<List<PackageSetupInfoEntity>> GetPageList(Pagination pagination, string queryJson)
        {
            var expression = GetExpression(queryJson);
            pagination.Records = _dbContext.PackageSetupInfoEntitys.Where(expression).Count();
            var qry = _dbContext.PackageSetupInfoEntitys.Where(expression);
            if (pagination.Skip > 0)
            {
                qry.Skip(pagination.Skip);
            }
            if (pagination.Take > 0)
            {
                qry.Take(pagination.Take);
            }
            return qry.ToListAsync();
        }
        /// <summary>
        /// 获取表达式
        /// </summary>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        private Expression<Func<PackageSetupInfoEntity, bool>> GetExpression(string queryJson)
        {
            JObject queryParam = queryJson.ToJObject();
            var expression = LinqExtensions.True<PackageSetupInfoEntity>();
            return expression;
        }

        /// <summary>
        /// 获取新版本
        /// </summary>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public PackageSetupInfoEntity GetNewVersion(string version, int packageId)
        {
            PackageSetupInfoEntity entity = null;
            //获取比当前版本比较新的版本
            var lst = _dbContext.PackageSetupInfoEntitys.ToList()
                .Where(n => new Version(n.Version) >= new Version(version)
                 && n.PackageId == packageId)
                .OrderBy(n => new Version(n.Version)).ToList();
            if (lst.Count() > 1)
            {
                int count = lst.Count;
                for (int i = 1; i < count; i++)
                {
                    entity = lst[i];
                    //判断是否获取最新
                    if (entity.IsGetLast == false)
                    {
                        break;
                    }
                }
            }
            return entity;
        }

        #endregion

        #region 保存数据
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Task<int> InsertData(PackageSetupInfoEntity entity)
        {
            entity.Create();
            _dbContext.Entry(entity).State = EntityState.Added;
            return _dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Task<int> UpdateData(string keyValue, PackageSetupInfoEntity entity)
        {
            try
            {
                entity.Modify();
                var oldEntity = _dbContext.PackageSetupInfoEntitys.FirstOrDefaultAsync(n => n.SetupId == Convert.ToInt32(keyValue)).Result;
                Dictionary<string, object> lstNew = BackupClientFileEntity.GetCacheProps(entity);
                foreach (var item in lstNew)
                {
                    if (!_dbContext.Entry(oldEntity).Property(item.Key).Metadata.IsPrimaryKey())
                    {
                        _dbContext.Entry(oldEntity).Property(item.Key).CurrentValue = item.Value;
                    }
                }
                if (!_dbContext.ChangeTracker.HasChanges())
                {
                    return Task.FromResult<int>(1);
                }
                else
                {
                    return _dbContext.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public Task<int> RemoveData(string keyValue)
        {
            int key = Convert.ToInt32(keyValue);
            var entity = _dbContext.PackageSetupInfoEntitys.FirstOrDefaultAsync(n => n.SetupId == key).Result;
            if (entity != null)
            {
                _dbContext.PackageSetupInfoEntitys.Remove(entity);
                //_dbContext.Entry(entity).State = EntityState.Deleted;
                return _dbContext.SaveChangesAsync();
            }
            else
            {
                return Task.FromResult<int>(0);
            }
        }
        #endregion
    }
}
